package com.sz.mes.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.V;
import com.diboot.core.vo.JsonResult;
import com.sz.mes.entity.PurchaseOrder;
import com.sz.mes.entity.SaleOrder;
import com.sz.mes.entity.TableHead;
import com.sz.mes.mapper.SaleOrderMapper;
import com.sz.mes.mapper.TableHeadMapper;
import com.sz.mes.service.SaleOrderService;
import com.sz.mes.service.impl.BaseCustomServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 销售订单相关Service实现
 *
 * @author hem
 * @version 1.0
 * @date 2023-09-05
 * Copyright © szhs
 */
@Service
@Slf4j
public class SaleOrderServiceImpl extends BaseCustomServiceImpl<SaleOrderMapper, SaleOrder> implements SaleOrderService {
    private final SaleOrderMapper saleOrderMapper;
    private final TableHeadMapper tableHeadMapper;

    public SaleOrderServiceImpl(SaleOrderMapper saleOrderMapper, TableHeadMapper tableHeadMapper) {
        this.saleOrderMapper = saleOrderMapper;
        this.tableHeadMapper = tableHeadMapper;
    }


    public JsonResult insert(SaleOrder entity) {
        SaleOrder saleOrder = new SaleOrder();
        saleOrder.setExcelData(entity.getExcelData());
        try {
//            productTaskMapper.insert(productTask);
            if (saleOrder.getExcelData() != null) {
                return dataProcess(saleOrder.getExcelData(), saleOrder.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return JsonResult.OK("导入数据成功");
    }

    //Excel 数据解析导入基础表
    JsonResult dataProcess(String excelData, Long purchaseOrderId) throws ParseException {
        //mapList 获取到所有的数据
        ArrayList<Map<String, String>> mapList = new ArrayList<>();


        //hashMap 表头对应的 序号
        HashMap<String, String> hashMap = new HashMap<>();
        //获取表头
        TableHead tableHead = tableHeadMapper.selectById(5);

        String data = tableHead.getData();
//        String replaceAll = data.replaceAll("\\\\", "");
//        System.out.println(data);
//        System.out.println(replaceAll);

        JSONObject jsonObject = JSONObject.parseObject(tableHead.getData());
        for (Object map : jsonObject.entrySet()) {
//            hashMap.put(String.valueOf(((Map.Entry)map).getValue()),String.valueOf(((Map.Entry)map).getKey()));
            hashMap.put(String.valueOf(((Map.Entry) map).getKey()), String.valueOf(((Map.Entry) map).getValue()));
        }

        //获取完表头信息后清楚数据，给其他数据用
        mapList.clear();

        System.out.println("excelData:" + excelData);

        //json转为List
        JSONArray objects = JSONObject.parseArray(excelData);
//        JSONArray objects = JSONObject.parseArray(JSONObject.toJSONString(excelData));
        for (Object object : objects) {
            HashMap<String, String> map1 = JSONObject.parseObject(JSONObject.toJSONString(object), HashMap.class);
            mapList.add(map1);
        }

        System.out.println("mapList:" + mapList);

        for (Map map : mapList) {
            System.out.println(map);
            //任务单
            SaleOrder saleOrder = new SaleOrder();
            saleOrder.setMaterialFinancial((String) map.get(hashMap.get("料品财务分类")));
            saleOrder.setProductNum((String) map.get(hashMap.get("料号")));
            saleOrder.setClientName((String) map.get(hashMap.get("客户简称")));
            saleOrder.setBusinessManager(((String) map.get(hashMap.get("业务负责人"))));
            saleOrder.setOrderNum((String) map.get(hashMap.get("订单号")));
            saleOrder.setOrderRow((String) map.get(hashMap.get("订单行号")));
            saleOrder.setSpecification((String) map.get(hashMap.get("料品规格")));
            saleOrder.setUnit((String) map.get(hashMap.get("销售订单行.料品.料品.库存主单位")));
            saleOrder.setProductName((String) map.get(hashMap.get("料品名称")));

//            saleOrder.setOrderQuantity((Integer) map.get(hashMap.get("订单数量")));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (!" ".equals(map.get(hashMap.get("下单日期"))) && !" ".equals(map.get(hashMap.get("合同要求日期")))) {
                String buyTime = (String) (map.get(hashMap.get("下单日期")));
                String contractDemandTime = (String) (map.get(hashMap.get("合同要求日期")));
                Date buyDate = sdf.parse(buyTime);
                Date contractDemandDate = sdf.parse(contractDemandTime);
                saleOrder.setBuyDate(buyDate);
                saleOrder.setContractDemandDate(contractDemandDate);
            }
//            saleOrder.setBuyDate((Date) map.get(hashMap.get("下单日期")));
//            saleOrder.setContractDemandDate((Date) map.get(hashMap.get("合同需求日期")));
//            saleOrder.setUnshippedGoodsQuantity((Integer) map.get(hashMap.get("未出货数量")));
//            saleOrder.setTotalShipmentQuantity(((Integer) map.get(hashMap.get("累计出货数量"))));
            saleOrder.setClientPurchasePerson(((String) map.get(hashMap.get("客户采购员"))));
            saleOrder.setClientUser(((String) map.get(hashMap.get("客户使用人"))));
            saleOrder.setClientProductNum(((String) map.get(hashMap.get("客户物料号"))));
            saleOrder.setClientPicNum(((String) map.get(hashMap.get("客户图号"))));
            saleOrder.setClientFactoryCode(((String) map.get(hashMap.get("客户工厂代码"))));
            saleOrder.setClientLocation(((String) map.get(hashMap.get("客户库位"))));
            saleOrder.setMaterialDescription(((String) map.get(hashMap.get("物料描述"))));
            saleOrder.setDeliveryAddress(((String) map.get(hashMap.get("收货地址"))));
            saleOrder.setCustomerName(((String) map.get(hashMap.get("订货客户.客户名称"))));


            Integer orderQuantity = (Integer) map.get(hashMap.get("订单数量"));
//            Integer taskQuantity = (Integer) map.get(hashMap.get("生产数量"));
            if (orderQuantity != 0) {
                saleOrder.setOrderQuantity(orderQuantity);
            } else {
                saleOrder.setOrderQuantity(0);
//                productTask.setQuantity(0);
            }

            Integer unshippedGoodsQuantity = (Integer) map.get(hashMap.get("未出货数量"));
//            Integer taskQuantity = (Integer) map.get(hashMap.get("生产数量"));
            if (unshippedGoodsQuantity != 0) {
                saleOrder.setUnshippedGoodsQuantity(unshippedGoodsQuantity);
            } else {
                saleOrder.setUnshippedGoodsQuantity(0);
//                productTask.setQuantity(0);
            }

            Integer totalShipmentQuantity = (Integer) map.get(hashMap.get("累计出货数量"));
//            Integer taskQuantity = (Integer) map.get(hashMap.get("生产数量"));
            if (totalShipmentQuantity != 0) {
                saleOrder.setTotalShipmentQuantity(totalShipmentQuantity);
            } else {
                saleOrder.setTotalShipmentQuantity(0);
//                productTask.setQuantity(0);
            }

            try {
//                saleOrder.setExcelData(excelData);
                saleOrderMapper.insert(saleOrder);
            } catch (Exception e) {
                return JsonResult.FAIL_OPERATION("插入失败" + e.getMessage());
            }
            //任务单处理结束
        }

        return JsonResult.OK("数据导入成功");
    }


    @Override
    public List<String> filterDuplicate(List<String> orderNumAndRowList) {
        if (V.isEmpty(orderNumAndRowList)) {
            return Collections.emptyList();
        }
        List<String> trimDuplicateData = new ArrayList<>();
        List<String> duplicateData = saleOrderMapper.selectDuplicateData(orderNumAndRowList);
        for (String duplicateDatum : duplicateData) {
            String trim = duplicateDatum.trim();
            trimDuplicateData.add(trim);
        }
//        LambdaQueryWrapper<ProductTask> wrapper = new LambdaQueryWrapper<>();
//        wrapper.in(ProductTask::getSplice, receiptNumAndStockNumList);
//        List<String> receiptNumAndStockNumLists = getValuesOfField(productTaskQueryWrapper, ProductTask::getSplice);


        return trimDuplicateData;
    }
}
